import logging
import allure
import pytest
import requests
from api_keyword.api_key import ApiKey
from params.allParams import URL, URL2


# 逻辑层

class ApiCase:
    """登录接口"""

    # 参数化测试数据
    def test_login(self, userdata):
        # 初始化工具类
        apiKey = ApiKey()
        # 从测试数据中获取用户信息
        username = userdata['user']['username']  # 用户名
        password = userdata['user']['password']  # 密码
        expected_msg = userdata['msg']  # 预期响应消息
        test_title = userdata['title']  # 测试标题
        # 动态获取参数生成标题
        allure.dynamic.title(userdata['title'])
        with allure.step(f"发送登录请求，用户名：{username}，密码：{password}"):
            userInfo = {"username": username, "password": password}  # 准备请求数据
            url = f"{URL}/api/user/login"  # 构建完整的 URL
            # 使用封装的 ApiKey 类发送请求
            response = apiKey.post(
                url=url,
                json=userInfo,
                headers={"Content-Type": "application/json"}
            )
        with allure.step(f"接口返回信息校验"):
            logging.info(f'登录接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            logging.info(f"测试用例执行成功：{test_title}")

    """登录2"""

    def test_login2(self):
        allure.dynamic.title("登录2")
        apiKey = ApiKey()
        userInfo = {
            "username": "admin",
            "password": "8i4De25KlVQVwqTDgTNGqw=="
        }
        url = f"{URL}/api/user/login"
        response = apiKey.post(
            url=url,
            json=userInfo,
            headers={"Content-Type": "application/json"}
        )
        with allure.step(f"发送登录请求"):
            logging.info(f'登录接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            msg = apiKey.get_text(response.text, 'msg')
            logging.info(f"响应消息：{msg}")
            assert msg == '登录成功'

    """获取角色列表  /api/role/get"""

    def test_roleList(self, role_list, token_fix):
        allure.dynamic.title(role_list['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = role_list['title']  # 从测试数据中获取测试标题
        with allure.step('发送获取角色列表请求'):
            url = f"{URL}/api/role/get"  # 构建完整的 URL
            json = {
                "wheres": role_list['role_list']['wheres'],
                "sorts": role_list['role_list']['sorts'],
                "pageIndex": role_list['role_list']['pageIndex'],
                "pageSize": role_list['role_list']['pageSize']
            }
            headers = {
                'token': token,
                'uid': str(uid),
            }
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'获取角色列表接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = role_list['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            logging.info(f"测试用例执行成功：{test_title}")
        return response

    """添加角色  /api/role/add"""

    def test_addrole(self, addrole, token_fix):
        allure.dynamic.title(addrole['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = addrole['title']  # 测试标题
        logging.info(f"\n开始执行测试用例：{test_title}")
        with allure.step(f"发送获取角色列表请求"):
            # 准备请求数据
            json = {
                "state": addrole['addrole']['state'],
                "role_name": addrole['addrole']['role_name'],
                "sort": addrole['addrole']['sort'],
                "remarks": addrole['addrole']['remarks']
            }
            url = f"{URL}/api/role/add"  # 构建完整的 URL
            headers = {
                'token': token,
                'uid': uid,
            }
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'获取角色列表接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = addrole['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            print(f"测试用例执行成功：{test_title}")
        return response

    """删除角色01  /api/role/del"""

    def test_delrole(self, delrole, token_fix):
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        allure.dynamic.title(delrole['title'])  # 动态获取参数生成标题
        test_title = delrole['title']  # 测试标题
        with allure.step(f"发送删除角色请求"):
            # 准备请求数据
            json = {
                "id": delrole['delrole']['id'],
            }
            url = f"{URL}/api/role/del"  # 构建完整的 URL
            headers = {'token': token, 'uid': uid}
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'删除角色接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = delrole['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            logging.info(f"测试用例执行成功：{test_title}")
        return response

    """获取权限列表"""

    def test_authList(self, authlist, token_fix):
        allure.dynamic.title(authlist['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = authlist['title']  # 从测试数据中获取测试标题
        with allure.step('发送获取权限列表请求'):
            url = f"{URL}/api/role/get"  # 构建完整的 URL
            json = {
                "wheres": authlist['authlist']['wheres'],
                "sorts": authlist['authlist']['sorts'],
                "pageIndex": authlist['authlist']['pageIndex'],
                "pageSize": authlist['authlist']['pageSize']
            }
            headers = {
                'token': token,
                'uid': uid,
            }
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'获取权限列表接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = authlist['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            logging.info(f"测试用例执行成功：{test_title}")
        return response

    """添加权限"""

    def test_addauth(self, addauth, token_fix):
        allure.dynamic.title(addauth['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = addauth['title']  # 测试标题
        with allure.step(f"{test_title}"):
            # 准备请求数据
            json = {
                "auth_url": addauth['addauth']['auth_url'],
                "auth_name": addauth['addauth']['auth_name'],
                "remarks": addauth['addauth']['remarks'],
                "cate_id": addauth['addauth']['cate_id']
            }
            url = f"{URL}/api/auth/add"  # 构建完整的 URL
            headers = {
                'token': token,
                'uid': uid,
            }
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'添加权限接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = addauth['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
        return response

    """删除权限  /api/auth/del"""

    def test_delauth(self, token_fix):
        allure.dynamic.title("删除权限接口ids参数不存在，删除0条数据")  # 动态获取参数生成标题
        apiKey, token, res, token_fix, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = "删除权限"  # 测试标题
        with allure.step(f"{test_title}"):
            # 准备请求数据
            json = {"id": 25}
            url = f"{URL}/api/auth/del"  # 构建完整的 URL
            headers = {'token': token, 'uid': uid}
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'删除权限接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = "成功删除了0条数据"  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f'预期消息：{expected_msg}\n'
                f'实际消息：{result.get("msg")}'
            )
        return response

    """获取权限分类列表  /api/auth/cate/get"""

    def test_authCateList(self, authCateList, token_fix):
        allure.dynamic.title(authCateList['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = authCateList['title']  # 从测试数据中获取测试标题
        with allure.step('发送获取权限分类列表请求'):
            url = f"{URL}/api/auth/cate/get"  # 构建完整的 URL
            json = {
                "wheres": authCateList['authCateList']['wheres'],
                "sorts": authCateList['authCateList']['sorts'],
                "pageIndex": authCateList['authCateList']['pageIndex'],
                "pageSize": authCateList['authCateList']['pageSize']
            }
            headers = {
                'token': token,
                'uid': uid,
            }
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'获取权限分类列表接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = authCateList['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            logging.info(f"测试用例执行成功：{test_title}")
        return response

    """添加权限分类  /api/auth/cate/add"""

    def test_addAuthCate(self, addAuthCate, token_fix):
        allure.dynamic.title(addAuthCate['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = addAuthCate['title']  # 测试标题
        with allure.step(f"{test_title}"):
            # 准备请求数据
            json = {
                "cate_name": addAuthCate['addAuthCate']['cate_name'],
                "remarks": addAuthCate['addAuthCate']['remarks'],
                'is_show': addAuthCate['addAuthCate']['is_show'],
                'sort': addAuthCate['addAuthCate']['sort']
            }
            url = f"{URL}/api/auth/cate/add"  # 构建完整的 URL
            headers = {
                'token': token,
                'uid': uid,
            }
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'添加权限分类接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = addAuthCate['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            logging.info(f"测试用例执行成功：{test_title}")
        return response

    """删除权限分类  /api/auth/cate/del"""

    def test_delAuthCate(self, delAuthCate, token_fix):
        allure.dynamic.title(delAuthCate['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = delAuthCate['title']  # 测试标题
        with allure.step(f"{test_title}"):
            # 准备请求数据
            json = {"ids": delAuthCate['delAuthCate']['ids']}
            url = f"{URL}/api/auth/cate/del"  # 构建完整的 URL
            headers = {'token': token, 'uid': uid}
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'删除权限分类接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = delAuthCate['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            logging.info(f"测试用例执行成功：{test_title}")
        return response

    """修改权限分类  /api/auth/cate/update"""

    def test_updateAuthCate(self, updateAuthCate, token_fix):
        allure.dynamic.title(updateAuthCate['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = updateAuthCate['title']  # 测试标题
        with allure.step(f"{test_title}"):
            # 准备请求数据
            json = {
                "cate_name": updateAuthCate['updateAuthCate']['cate_name'],
                "remarks": updateAuthCate['updateAuthCate']['remarks'],
                'is_show': updateAuthCate['updateAuthCate']['is_show'],
                'sort': updateAuthCate['updateAuthCate']['sort']
            }
            url = f"{URL}/api/auth/cate/update"  # 构建完整的 URL
            headers = {'token': token, 'uid': uid}
            response = apiKey.post(url=url, headers=headers, json=json)  # 发送请求
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'修改权限分类接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = updateAuthCate['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            logging.info(f"测试用例执行成功：{test_title}")
        return response

    """获取日志列表"""

    def test_logList(self, loglist, token_fix):
        allure.dynamic.title(loglist['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = loglist['title']  # 测试标题
        with allure.step(f"{test_title}"):
            # 准备请求数据
            json = {
                "wheres": loglist['loglist']['wheres'],
                "sorts": loglist['loglist']['sorts'],
                "pageIndex": loglist['loglist']['pageIndex'],
                "pageSize": loglist['loglist']['pageSize']
            }
            url = f"{URL}/api/user/log/get"  # 构建完整的 URL
            headers = {'token': token, 'uid': uid}
            response = apiKey.post(url=url, headers=headers, json=json)  # 发送请求
        with allure.step(f"接口返回信息校验接打印"):
            logging.info(f'获取日志列表接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = loglist['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            logging.info(f"测试用例执行成功：{test_title}")
        return response

    """获取文件列表"""

    def test_fileList(self, filelist, token_fix):
        allure.dynamic.title(filelist['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = filelist['title']  # 测试标题
        with allure.step(f"{test_title}"):
            # 准备请求数据
            json = {
                "wheres": filelist['filelist']['wheres'],
                "sorts": filelist['filelist']['sorts'],
                "pageIndex": filelist['filelist']['pageIndex'],
                "pageSize": filelist['filelist']['pageSize']
            }
            url = f"{URL}/api/file/get"  # 构建完整的 URL
            headers = {'token': token, 'uid': uid}
            response = apiKey.post(url=url, headers=headers, json=json)  # 发送请求
        with allure.step(f" 接口返回信息校验接打印"):
            logging.info(f'获取文件列表接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = filelist['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
            logging.info(f"测试用例执行成功：{test_title}")
        return response

    """删除文件"""

    def test_delFile(self, delfile, token_fix):
        allure.dynamic.title(delfile['title'])  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        test_title = delfile['title']  # 测试标题
        with allure.step(f"{test_title}"):
            # 准备请求数据
            json = {
                "ids": delfile['delfile']['ids']
            }
            url = f"{URL}/api/file/del"  # 构建完整的 URL
            headers = {'token': token, 'uid': uid}
            response = apiKey.post(url=url, headers=headers, json=json)  # 发送请求
        with allure.step(f" 接口返回信息校验接打印"):
            logging.info(f'删除文件接口请求响应信息:{response.text}')
            logging.info(f'响应状态码:{response.status_code}')
            logging.info(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            logging.info(f"响应消息：{msg}")
            # 断言响应消息
            expected_msg = delfile['msg']  # 预期响应消息
            assert result.get('msg') == expected_msg, (
                f"响应消息与预期不符\n"
                f"预期消息：{expected_msg}\n"
                f"实际消息：{result.get('msg')}"
            )
